﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customize.Excel
{

    public static class ExcelExtensions
    {
        /// <summary>
        /// 格式化Excel文件名，根据Excel类型，为Excel增加后缀。
        /// </summary>
        /// <param name="fileName">未格式化的文件名</param>
        /// <param name="officeType">Excel类型</param>
        /// <returns>格式化后的Excel文件名。</returns>
        public static string FormatFileName(String fileName, OfficeType officeType)
        {
            if (String.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");
            var ext = officeType == OfficeType.Office2007 ? ".xlsx" : ".xls";
            var name = fileName;
            if (!fileName.EndsWith(ext, StringComparison.CurrentCultureIgnoreCase))
            {
                name += ext;
            }
            return name;
        }

        public static int ToColumnIndex(this string columnName)
        {
            int rtn = 0;
            int powIndex = 0;

            for (int i = columnName.Length - 1; i >= 0; i--)
            {
                int tmpInt = columnName[i];
                tmpInt -= 64;

                rtn += (int)Math.Pow(26, powIndex) * tmpInt;
                powIndex++;
            }

            return rtn;
        }
        public static string ToExcelChar(this int columnIndex)
        {
            string rtn = string.Empty;
            List<int> iList = new List<int>();

            //To single Int
            while (columnIndex / 26 != 0 || columnIndex % 26 != 0)
            {
                iList.Add(columnIndex % 26);
                columnIndex /= 26;
            }

            //Change 0 To 26
            for (int j = 0; j < iList.Count - 1; j++)
            {
                if (iList[j] == 0)
                {
                    iList[j + 1] -= 1;
                    iList[j] = 26;
                }
            }

            //Remove 0 at last
            if (iList[iList.Count - 1] == 0)
            {
                iList.Remove(iList[iList.Count - 1]);
            }

            //To String
            for (int j = iList.Count - 1; j >= 0; j--)
            {
                char c = (char)(iList[j] + 64);
                rtn += c.ToString();
            }

            return rtn;
        }
    }
}
